import { type DotenvParseOutput } from 'dotenv'

const PREFIX_VARS_ENV = /^PROJECT_APP_/i;
const PORT = 'PORT'

function getClientEnvironment(envObj: DotenvParseOutput, baseEnv: string) {
  // 获取所有的环境变量，然后过滤出以 `PROJECT_APP_` 开头的环境变量 或 PORT 变量
  const raw: DotenvParseOutput = Object.keys(envObj)
    .filter((key) => PREFIX_VARS_ENV.test(key) || key === PORT || key === 'NODE_ENV')
    .reduce(
      (env: DotenvParseOutput, key: string) => {
        env[key] = envObj[key];
        return env;
      },
      {
        BASE_ENV: baseEnv,
      }
    );

  const stringified = {
    "process.env": Object.keys(raw).reduce((env: DotenvParseOutput, key: string) => {
      env[key] = JSON.stringify(raw[key]);
      return env;
    }, {} as DotenvParseOutput),
  };

  return { raw, stringified };
}

export {
  PREFIX_VARS_ENV,
  PORT,
}

export default getClientEnvironment;
